package com.zxx.coolweather._wuguan2.async;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 使用：
 * MultiAsynctaskNetwork network = new MultiAsynctaskNetwork(networkInterface);
 * network.execute();
 *
 * @author zxx on 2022/1/12
 */
public class MultiAsynctaskNetwork extends MultiAsynctask<Void, Integer, String> {

    private NetworkInterface mInterface;

    public MultiAsynctaskNetwork(NetworkInterface mInterface) {
        this.mInterface = mInterface;
    }

    @Override
    protected String onExecuteTask(Void... parms) {
        HttpURLConnection connection = null;

        try {
            URL url = new URL("https://www.wanandroid.com/article/list/1/json");
            connection = (HttpURLConnection) url.openConnection();
            //connection.setRequestMethod("POST");

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                int len = 0;
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                InputStream inputStream = new BufferedInputStream(connection.getInputStream());

                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }

                inputStream.close();
                outputStream.flush();
                inputStream.close();

                return new String(outputStream.toByteArray());
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return "请求网络失败";
    }

    @Override
    protected void onResult(String s) {
        // 拿到执行结果，直接更新UI
        mInterface.onResult(s);
    }
}
